package meb

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gotool/gobjectid"
	"github.com/mosongcc/gotool/gtime"
	"gorm.io/gorm"
	"time"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// OrderCrete 创建订单
func (ctl *Controller) OrderCrete(ctx *gin.Context) (err error) {
	var (
		token = hgin.CtxToken(ctx)
		uid   = token.Uid
		args  = hgin.ApiReq[TradeCreteArgs](ctx)
	)
	if args.ProdId == "" {
		err = errors.New("产品编号不能为空")
		return
	}

	// 如果用户存在待支付订单，直接返回
	var order model.Order
	if err = ctl.db.Where("uid = ? and prod_id = ? and status = ? and pay_timeout > ?", uid, args.ProdId, model.ORDER_STATUS_PENDING, time.Now().Add(3*time.Minute).Format(gtime.LayoutT14)).First(&order).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return
		}
	}
	if order.OrderId != "" {
		hgin.ApiRes(ctx, TradeCreteBody{OrderId: order.OrderId})
		return
	}

	//产品信息
	var prod model.Product
	if err = ctl.db.Where("prod_id = ? and status = ? ", args.ProdId, model.ProductStatus_UP).Take(&prod).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			err = errors.New("产品编号不存在")
			return
		}
		return
	}

	//创建订单
	order = model.Order{
		OrderId:    gobjectid.Hex(),
		Uid:        uid,
		Status:     model.ORDER_STATUS_PENDING,
		TxnDate:    gtime.NowF8(),
		TxnAmt:     prod.UnitPrice,
		PayTimeout: time.Now().AddDate(0, 0, 1).Format(gtime.LayoutT14),
		ProdId:     args.ProdId,
		ProdName:   prod.ProdName,
		ProdNum:    1,
		ProdPrice:  0,
		ProdType:   prod.Type,
		ProdThumb:  prod.Thumb,
		Domain:     ctx.Request.Host,
		Ip:         hgin.RemoteIP(ctx),
		Ctime:      gtime.NowF14(),
		Mtime:      gtime.NowF14(),
	}
	err = ctl.db.Create(order).Error
	if err != nil {
		return
	}

	hgin.ApiRes(ctx, TradeCreteBody{OrderId: order.OrderId})
	return
}

type TradeCreteArgs struct {
	ProdId string `json:"prod_id"` //产平编号
}

type TradeCreteBody struct {
	OrderId string `json:"order_id"`
	PayUrl  string `json:"pay_url"` // 支付链接，用户扫码支付
}
